package com.lepu.pcecg500;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lepu.ecg500.ECGDiag;
import com.lepu.pcecg500.http.EcgHttpBean;
import com.lepu.pcecg500.http.HttpDataBean;
import com.lepu.pcecg500.http.HttpResultBean;
import com.lepu.pcecg500.http.HttpUrl;
import com.lepu.pcecg500.http.UserInfoBean;
import com.lepu.pcecg500.util.Constant;
import com.lepu.pcecg500.util.EcgTable;
import com.lepu.pcecg500.util.FileUtils;
import com.lepu.pcecg500.util.FinalDbManager;
import com.lepu.pcecg500.util.GwtjDbBean;
import com.lepu.pcecg500.util.GwtjDbUtil;
import com.lepu.pcecg500.util.ImageTool;
import com.lepu.pcecg500.util.OpenHelper;
import com.permissionx.guolindev.PermissionX;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import rxhttp.RxHttp;

public class MainActivity extends AppCompatActivity {

    private EditText et_code;
    private Button btn_start;
    private Button btn_clear;
    private ImageView iv_setting;
    private LinearLayout ll_blood_lipid_history;
    private FinalDbManager finalDbManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        ECGDiag.result = "";
        iv_setting = findViewById(R.id.iv_setting);
        et_code = findViewById(R.id.et_code);
        btn_start = findViewById(R.id.btn_start);
        btn_clear = findViewById(R.id.btn_clear);
        ll_blood_lipid_history = findViewById(R.id.ll_blood_lipid_history);

        et_code.setText("202403280008001");

        iv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, SettingActivity.class));
            }
        });
        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_code.setText("");
            }
        });
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String code = et_code.getText().toString().trim();
                if (!TextUtils.isEmpty(code)) {
//                    saveData("1", "1", "65", "心率正常", "");
                    requestHttpInfo(code);
//                    Intent intent = new Intent(MainActivity.this, JavaActivity.class)
//                            .putExtra("code", code);
//                    startActivityForResult(intent,1);
                } else {
                    ToastUtils.showShort("请输入条码号！");
                }
            }
        });

        ll_blood_lipid_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ECGHistoryActivity.class));
            }
        });

        PermissionX.init(this)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .setDialogTintColor(Color.parseColor("#008577"), Color.parseColor("#83e8dd"))
                .onExplainRequestReason((scope, deniedList) ->
                        scope.showRequestReasonDialog(
                                deniedList,
                                getString(R.string.hint),
                                getString(R.string.confirm),
                                getString(R.string.cancel)
                        ))
                .onForwardToSettings((scope, deniedList) ->
                        scope.showForwardToSettingsDialog(
                                deniedList,
                                getString(R.string.permission),
                                getString(R.string.confirm),
                                getString(R.string.cancel)
                        ))
                .request((allGranted, grantedList, deniedList) -> {
                    initDb();
                });
        FileUtils.isPathExist();
    }

    private void initDb() {
        Log.e("xiaoxin", "initDb: " );
        FileUtils.isPathExist();
        FileUtils.copyAddressDB(MainActivity.this,
                GwtjDbUtil.getInnerSDCardPath(),"info.db");

       new Handler().postDelayed(new Runnable() {
           @Override
           public void run() {
               finalDbManager = FinalDbManager.getInstance(MainActivity.this);
           }
       }, 4000);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                String ecgFile = data.getStringExtra("ecgFile");
                if (!TextUtils.isEmpty(ecgFile)) {
                    try {
                        String[] strings = ecgFile.split(";");

                        saveData("1","0", strings[0], strings[1], strings[2]);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     *
     * @param state 0成功 1失败
     * @param type 1自动上传 0手动上传
     * @param hr
     * @param conclusion
     * @param ecgPath
     */
    private void saveData(String state, String type, String hr, String conclusion, String ecgPath) {

        if (finalDbManager == null) {
            finalDbManager = FinalDbManager.getInstance(MainActivity.this);
        }
        Date date = new Date();
        String date2Str = TimeUtils.date2String(date, "yyyy-MM-dd HH:mm:ss");
        String time = TimeUtils.date2String(date, "yyyy-MM-dd");
        List<EcgTable> list = finalDbManager.findAllByWhereInInfoDB(EcgTable.class,
                "Code='" + et_code.getText().toString().trim()
                        + "' and addTime='" + time + "'");
        if (list.size() > 0) {
            EcgTable ecgTable = list.get(0);
            ecgTable.setHr(hr);
            ecgTable.setConclusion(conclusion);
            ecgTable.setPath(ecgPath);
            ecgTable.setAddTime(time);
            ecgTable.setAddDate(date2Str);
            ecgTable.setState(state);
            ecgTable.setType(type);
            finalDbManager.updataInInfoDB(ecgTable);
            ToastUtils.showShort("保存成功！");
            requestHttp(ecgTable);
        } else {
            EcgTable gwtjDbBean = new EcgTable();
            gwtjDbBean.setCode(et_code.getText().toString().trim());
            gwtjDbBean.setHr(hr);
            gwtjDbBean.setConclusion(conclusion);
            gwtjDbBean.setPath(ecgPath);
            gwtjDbBean.setAddTime(time);
            gwtjDbBean.setAddDate(date2Str);
            gwtjDbBean.setState(state);
            gwtjDbBean.setType(type);
            finalDbManager.save(gwtjDbBean);
//            GwtjDbUtil.insertEcgDb(gwtjDbBean);
            ToastUtils.showShort("保存成功！");
            requestHttp(gwtjDbBean);
        }

    }

    private void requestHttp(EcgTable gwtjDbBean) {
        EcgHttpBean ecgHttpBean = new EcgHttpBean();
        ecgHttpBean.setCold(gwtjDbBean.getCode());
        ecgHttpBean.setHR(gwtjDbBean.getHr());
        ecgHttpBean.setXDdiagnosis(gwtjDbBean.getConclusion());
        ecgHttpBean.setDTime(gwtjDbBean.getAddDate());

        if (!TextUtils.isEmpty(gwtjDbBean.getPath())) {
            String base64 = ImageTool.imageToBase64(gwtjDbBean.getPath());
            ecgHttpBean.setPicBuf("data:image/png;base64," + base64);
        }

        HttpDataBean httpDataBean = new HttpDataBean();
        httpDataBean.setQueryType("Check");
        httpDataBean.setData(ecgHttpBean);
        RxHttp.postJson(HttpUrl.getHttpUrl() + HttpUrl.ecgUrl)
                .addAll(GsonUtils.toJson(httpDataBean))
                .asClass(HttpResultBean.class)
                .subscribe(resultBean -> {
                    ToastUtils.showShort(resultBean.getResponseMsg() + "");
                    LogUtils.e(resultBean);
                    if (resultBean.getResponseCode() == 200) {
                        gwtjDbBean.setState("0");
                        gwtjDbBean.setType("0");
                        updateDbData(gwtjDbBean);
                    }
                }, throwable -> {
                    ToastUtils.showShort(throwable.getMessage() + "");
                    LogUtils.e(throwable.getMessage());
                });
    }

    private void updateDbData(EcgTable bloodLipidTable) {
        try {
            String where = "code = '" + bloodLipidTable.getCode() + "' AND addTime = '" + bloodLipidTable.getAddTime() + "'";
            finalDbManager.updataInInfoDB(bloodLipidTable,where);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void requestHttpInfo(String code) {
        if (TextUtils.isEmpty(code)) {
            return;
        }
        HttpDataBean httpDataBean = new HttpDataBean();
        httpDataBean.setQueryType("");
        httpDataBean.setData(code);
        RxHttp.postJson(HttpUrl.getHttpUrl() + HttpUrl.SelectCold)
                .addAll(GsonUtils.toJson(httpDataBean))
                .asClass(HttpResultBean.class)
                .subscribe(resultBean -> {
//                    ToastUtils.showShort(resultBean.getResponseMsg() + "");
                    LogUtils.e(resultBean);
                    if (resultBean.getResponseCode() == 200) {
                        UserInfoBean userInfoBean = GsonUtils.fromJson(resultBean.getResponseData().toString(), UserInfoBean.class);
                        if (userInfoBean != null) {
                            int age = getAge(userInfoBean.getCardID());
                            String sex = "";
                            if ("1".equals(userInfoBean.getUserSex())) {
                                sex = "男";
                            } else if ("2".equals(userInfoBean.getUserSex())) {
                                sex = "女";
                            }
                            Intent intent = new Intent(MainActivity.this, JavaActivity.class);
                            intent.putExtra("code", code);
                            intent.putExtra("name", userInfoBean.getUserName());
                            intent.putExtra("sex", sex);
                            intent.putExtra("age", age + "");
                            ECGDiag.result = "";
                            startActivityForResult(intent,1);
                            Log.e("xiaoxin", "requestHttp: " + resultBean.getResponseData() );
                            Log.e("xiaoxin", "requestHttp: " + userInfoBean.toString() );
                        }
                    }
                }, throwable -> {
                    ToastUtils.showShort("条码号错误！");
                    LogUtils.e(throwable.getMessage());
                });
    }

    private int getAge(String idNumber) {
        // 获取当前日期
        try {
            Calendar calendar = Calendar.getInstance();
            int currentYear = calendar.get(Calendar.YEAR);
            // 提取身份证号中的出生日期
//            String idNumber = "11010119800101234X";
            String birthDateStr = idNumber.substring(6, 14);
            // 将出生日期字符串转换为Date类型
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Date birthDate = dateFormat.parse(birthDateStr);
            // 计算年龄
            calendar.setTime(birthDate);
            int birthYear = calendar.get(Calendar.YEAR);
            int age = currentYear - birthYear;
            return age;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

}